package com.xdwanj.service.impl;

import com.xdwanj.service.UnboxService;
import com.xdwanj.util.DirTraversal;
import com.xdwanj.util.FileUtil;
import com.xdwanj.util.ZipUtil;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class UnboxServiceImpl implements UnboxService {

    @Override
    public void UnboxZipAndUpZip(File targetFileDir) {
        LinkedList<File> zipFileDirLink = new LinkedList<>();
        List<String> upZipDirList = new ArrayList<>();

        // 判断传入的是文件夹还是文件
        if (targetFileDir.isDirectory()) {
            zipFileDirLink = DirTraversal.noRecFiles(targetFileDir.getPath());
        } else {
            zipFileDirLink.add(targetFileDir);
        }

        // 筛选出压缩包列表
        for (File file : zipFileDirLink) {
            // 筛选zip压缩文件
            if (file.getPath().contains(".zip")) {
                upZipDirList.add(file.getPath());
            }
        }

        upZipDirList.forEach(s -> System.out.println("s = " + s));

        // 对每个压缩包处理
        for (String oldDirString : upZipDirList) {
            String newDirString = oldDirString.substring(0, oldDirString.indexOf(".zip"));
            File oldDirFile = new File(oldDirString);
            File newDirFile = new File(newDirString);

            System.out.println("oldDirString = " + oldDirString);
            System.out.println("newDirString = " + newDirString);

            try {
                // 判断压缩文件中只有一个根文件夹
                if (IsAloneDir(oldDirFile)) {

                    if (!newDirFile.exists()) {
                        newDirFile.mkdir();
                    }

                    ZipUtil.upZipFile(oldDirFile, newDirString);
                    FileUtil.deleteDir(oldDirFile);

                    ArrayList<File> files = DirTraversal.listFiles(newDirString);
                    ZipUtil.zipFiles(files, oldDirFile);
                    FileUtil.deleteDir(newDirFile);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    private boolean IsAloneDir(File dirFile) throws IOException {
        List<String> oldList = ZipUtil.getEntriesNames(dirFile);
        Set<String> newSet = null;
        for (int i = 0; i < oldList.size(); i++) {
            System.out.println("oldList.get(i) = " + oldList.get(i));
            try {
                oldList.set(i, oldList.get(i).substring(0, oldList.get(i).indexOf("\\")));
            } catch (Exception e) {
                return false;
            }
        }
        newSet = new HashSet<>(oldList);

        return newSet.size() == 1;
    }

}
